<template>
  <div>
    <!-- 用户管理工具栏 -->
    <el-form ref="searchForm" :model="searchForm" :inline="true">
      <el-form-item>
        <el-input v-model="searchForm.username" placeholder="请输入要搜索的用户名称"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="loadUserList()">搜索</el-button>
        <el-button type="primary" @click="dialogFormVisible=true">新建</el-button>

        <el-popconfirm title="确认要批量删除这些用户信息吗">
            <el-button slot="reference" type="danger" :disabled="deleteAllBtnStu">批量删除</el-button>
        </el-popconfirm>
      </el-form-item>
    </el-form>

    <!-- 新建或编辑用户的对话框 -->
    <el-dialog title="用户信息" :visible.sync="dialogFormVisible" width="600px">
       <el-form :model="UserForm" ref="UserForm" label-width="100px" :rules="UserRules">
        <el-form-item label="用户头像" label-width="100px">
          <!-- 将本地图片 上传阿里 文件服务器上面 -->
          <el-upload class="avatar-uploader" :action="'/sys/oss/upload'" :show-file-list="false" name="file" 
          :on-success="handleAvatarSuccess" :headers="headers" >
            <img v-if="UserForm.avatar" :src="UserForm.avatar" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="用户名" label-width="100px" prop="username">
          <el-input v-model="UserForm.username"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" label-width="100px" prop="email">
          <el-input v-model="UserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" label-width="100px" prop="tel">
          <el-input v-model="UserForm.tel"></el-input>
        </el-form-item>
         <el-form-item label="用户状态" label-width="100px" prop="statu">
          <el-radio-group v-model="UserForm.statu">
            <el-radio :label="0">禁用</el-radio>
            <el-radio :label="1">正常</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitUserForm('UserForm')">保存用户</el-button>
          <el-button @click="resetUserForm('UserForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 分配角色对话框 -->
    <el-dialog title="分配角色" :visible.sync="dialogRoleFormVisible" width="600px" @closed="resetRoleForm('UserRoleForm')">
      <el-form :model="UserRoleForm" ref="UserRoleForm">
        <el-tree show-checkbox :data="roleTreeData" ref="roleTree" node-key="id" :props="defaultProps" :default-expand-all="true" :check-strictly="true" >
        </el-tree>  
      </el-form>
      <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitRoleForm('UserRoleForm')">保存分配角色</el-button>
          <el-button @click="resetRoleForm('UserRoleForm')">重置</el-button>
        </div>   
    </el-dialog>

    <!-- 用户表格数据的显示 -->
    <el-table :data="tableData" style="width:100%;margin-bottom: 20px;" border :cell-style="{ padding:'2px' }" @selection-change="selectionChange">
      <el-table-column type="selection" width="50"></el-table-column>
      <el-table-column label="头像" width="55">
        <template slot-scope="scope">
          <el-avatar size="small" :src="scope.row.avatar"></el-avatar>
        </template>
      </el-table-column>
      <el-table-column prop="username" label="用户名" width="120"></el-table-column>
      <el-table-column label="角色">
        <template slot-scope="scope">
          <el-tag v-for="(role,index) in scope.row.roles" :key="role.id" style="margin-left:2px;">
            {{role.name}}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="email" label="邮箱" width="180"></el-table-column>
      <el-table-column prop="tel" label="电话" width="140"></el-table-column>
      <el-table-column prop="type" label="用户状态" width="90">
        <template slot-scope="scope">
          <el-tag size="mini" v-if="scope.row.statu===0" type="danger">禁用</el-tag>
          <el-tag size="mini" v-else-if="scope.row.statu===1" type="success">正常</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间">
        <template slot-scope="scope">
          {{ scope.row.created | fmtDate}}
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="280px">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="editRoleMethod(scope.row.id)">分配角色</el-button>
          <el-divider direction="vertical"></el-divider>
          <el-button type="text" size="small" @click="editUser(scope.row.id)">编辑</el-button>
          <el-divider direction="vertical"></el-divider>
          <!-- <el-popconfirm title="确定要重置该用户的密码吗" @confirm="resetPassword(scope.row.id,scope.row.username)">
            <el-button type="text" size="small" slot="reference">重置密码</el-button>
          </el-popconfirm> -->
          <el-button type="text" size="small" @click="resetPassword(scope.row.id,scope.row.username)">重置密码</el-button>
          <el-divider direction="vertical"></el-divider>
          <el-popconfirm title="确定要删除该用户数据吗" @confirm="deleteUser(scope.row.id)">
              <el-button size="small" type="text" slot="reference">删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页的页码 -->
    <el-pagination background layout="prev, pager, next,sizes,total,jumper" :total="total" :page-size="size"
    :page-sizes="[5,10,15,20,25]" :current-page="current" @size-change="sizeChangeHandler" @current-change="currentChangeHandler">
    </el-pagination>
  </div>
</template>

<script>
export default {
  data() {
    return {
      tableData:[],//用户表格的数据
      UserRules:{
         username:[{required: true, message:'请输入用户的名称', trigger: 'blur'}],
         email:[{required: true, message:'请输入邮箱地址', trigger: 'blur'}],
         tel:[{required: true, message:'请输入电话号码', trigger: 'blur'}],
         statu:[{required: true, message:'请选择用户状态', trigger: 'blur'}],
      },
      //新建或编辑用户 对话框表单对象
      UserForm:{
        avatar:'',  //用户头像图片 地址。(上传成功之后，回记录上传头像图片在服务器地址)
        username:'', //用户名
        email:'', //邮箱
        tel:'', //手机号
        statu:1, //用户状态
      },
      deleteAllBtnStu:true, //默认 批量删除的按钮 是否被禁用。
      dialogFormVisible:false, //新建或编辑用户的对话框是否显示
      dialogRoleFormVisible:false,  //分配角色的对话框是否显示
      searchForm:{
        username:'',  //可以进行用户名 搜索的关键词
      },
      UserRoleForm:{}, //用户分配角色对话框表单对象
      roleTreeData:[], //分配角色Tree控件数据
      total:0,
      size:10,
      current:1,
      defaultProps: {
          children: 'children', //不使用，因为角色信息不存在层级关系
          label: 'name'
      },
      headers:{
        token:JSON.parse(localStorage.getItem('TOKEN'))
      }
    }
  },
  created(){
    this.loadUserList();
    //加载树形控件 角色基础数据：
    this.$axios.get('/role/tree').then(response=>{
      this.roleTreeData = response.data.resultdata
    }).catch(e=>{ console.log(e); })
  },
  methods:{
    //分配角色按钮事件执行方法
    editRoleMethod(id){
        this.$axios.get('/user/info/'+id).then(response=>{
           let user = response.data.resultdata;
           this.UserRoleForm = user;   //UserRoleForm包含用户数据和该用户所具有角色数据
           //以及user所具备的角色信息
           let roleIds = [];
           user.roles.forEach( role =>{
            roleIds.push(role.id)
           });
           this.$refs.roleTree.setCheckedKeys(roleIds);  //选中树形控件中 用户所具备角色
        }).catch(e=>{ console.log(e); })

        this.dialogRoleFormVisible = true
    },
    //保存分配角色表单
    submitRoleForm(formName){
        //获得tree控件中设置 角色id。
        let roleIds = this.$refs.roleTree.getCheckedKeys();

        this.$axios.post('/user/role/'+this.UserRoleForm.id,roleIds).then(response=>{
              this.$message({
                showClose: true,
                message: response.data.resultdata,
                type:'success',
              });
              this.loadUserList();
              this.dialogRoleFormVisible = false
        }).catch(e=>{ console.log(e); })
    },
    //重置分配角色表单
    resetRoleForm(formName){
      this.$refs.roleTree.setCheckedKeys([]);
      this.UserRoleForm = {}
      this.$refs[formName].resetFields();
    },
    //重置用户密码方法
    resetPassword(id,username){
      this.$confirm('重置用户【'+username+'】的密码，是否继续执行该操作','重置密码提示',{
        confirmButtonText:'执行',
        cancelButtonText:'取消',
        type:'warning'
      }).then(()=>{
        //点击消息框 执行按钮，执行代码
        this.$axios.post('/user/repass/'+id).then(response=>{
              this.$message({
                showClose: true,
                message: response.data.resultdata,
                type:'success',
              });
        }).catch(e=>{ console.log(e); })
      });
    },
    //切换页码的方法
    currentChangeHandler(val){
      this.current = val;
      this.loadUserList();
    },
    //一页显示数据条数切换
    sizeChangeHandler(val){
      this.size = val;
      this.loadUserList();
    },
    //删除用户实现
    deleteUser(id){
      var roleIds = [];  //存储要删除的所有的角色id。单个删除数组存储就是一个id。
      id?roleIds.push(id):this.selection.forEach(role =>{
        roleIds.push(role.id)
      });

      this.$axios.post('/user/delete',roleIds).then(response=>{
              this.$message({
                showClose: true,
                message: response.data.resultdata,
                type:'success',
                onClose:()=>{    
                  this.loadUserList();  //重新加载角色的信息
                }
              });
      }).catch(e=>{ console.log(e); })
    },
    //编辑用户
    editUser(id){
      this.$axios.get('/user/info/'+id).then(response=>{
          this.UserForm = response.data.resultdata
          this.dialogFormVisible = true
        }).catch(e=>{ console.log(e); })
    },
    showInfo(){
      
    },
    //加载用户表格数据
    loadUserList(){
      this.$axios.get('/user/list',{
        params:{
			    name:this.searchForm.username, //搜索关键词
          current:this.current,  //页码
          size:this.size,  //一页显示多少条
		    }
      }).then(response=>{
          this.tableData = response.data.resultdata.records
          this.total = response.data.resultdata.total
          this.size = response.data.resultdata.size
          this.current = response.data.resultdata.current
      }).catch(e=>{ console.log(e); })
    },
    //重置新建或编辑用户表单
    resetUserForm(formName){
      this.UserForm = {}
      this.$refs[formName].resetFields();
    },
    //新建或编辑用户表单提交
    submitUserForm(formName){
      this.$refs[formName].validate((valid)=>{
        if(valid){
            this.$axios.post('/user/'+(this.UserForm.id?'update':'save'),this.UserForm).then(response=>{
                  this.$message({
                    showClose: true,
                    message: response.data.resultdata,
                    type:'success',
                  });
                  this.loadUserList();  
                  this.resetUserForm(formName);
                  this.dialogFormVisible = false;
            }).catch(e=>{ console.log(e); })
        }else{
          return false
        }
      })
    },
    //上传头像成功之后回调
    handleAvatarSuccess(response,file){
      //上传成功，从响应对象response中可以获得上传图片在服务器的地址。
      //组件上传回调 response 不需要.data。 这里response直接就是返回Result.
      //平时使用axios.返回response必须先response.data才是返回Result。
      this.UserForm.avatar = response.resultdata
    },
    //选中表格中 复选框触发的事件
    selectionChange(value){
      this.selection = value
      if(this.selection){
        this.deleteAllBtnStu = (this.selection.length === 0)
      }
    }
  }
}
</script>

<style scoped>
.avatar-uploader {
  border:1px solid #aeaeae;
  border-radius:3px;
  cursor:pointer;
  position:relative;
  overflow:hidden;
  width:150px;
}
.avatar-uploader-icon{
  font-size:28px;
  color:#aeaeae;
  width:150px;
  height:150px;
  line-height:150px;
  text-align:center;
}
</style>

